import React, { useState, useEffect } from 'react';
import { 
  Layout, 
  Tabs, 
  Button as AntButton, 
  Input, 
  Tooltip, 
  Empty, 
  Spin,
  App
} from 'antd';
import { 
  ArrowLeftOutlined,
  PlusOutlined, 
  UserOutlined, 
  HomeOutlined
} from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { Card } from '../../components/common/Card';
import { Button } from '../../components/common/Button';
import { tablesService, areasService } from '../../services';
import type { Table, Area } from '../../services';
import './OrderStationPage.css';

const { TabPane } = Tabs;
const { Search } = Input;

// 餐桌状态类型
type TableStatus = 'free' | 'occupied';

// 获取状态显示文本
const getStatusText = (status: TableStatus) => {
  switch (status) {
    case 'free':
      return '空闲';
    case 'occupied':
      return '使用中';
    default:
      return status;
  }
};

export const OrderStationPage: React.FC = () => {
  const [areaTab, setAreaTab] = useState<string>('all');
  const [searchQuery, setSearchQuery] = useState('');
  const [tables, setTables] = useState<Table[]>([]);
  const [areas, setAreas] = useState<Area[]>([]);
  const [loading, setLoading] = useState(true);
  const [areasLoading, setAreasLoading] = useState(true);
  const navigate = useNavigate();
  const location = useLocation();
  const { message } = App.useApp();

  // 加载餐桌和区域数据
  useEffect(() => {
    fetchTables();
    fetchAreas();
  }, []);

  // 从URL参数中获取tableId
  useEffect(() => {
    const params = new URLSearchParams(location.search);
    const tableId = params.get('tableId');
    if (tableId) {
      // 查找餐桌状态
      const table = tables.find(t => t.id === parseInt(tableId, 10));
      if (table) {
        const status: TableStatus = table.processingTrade ? 'occupied' : 'free';
        if (status === 'free') {
          // 如果是空闲餐桌，进入点餐页面
          navigateToOrderPage(table);
        } else if (status === 'occupied') {
          // 如果是就餐中餐桌，进入订单详情页面
          navigateToOrderDetail(table);
        } else {
          message.info(`餐桌${table.name}当前状态无法进行操作`);
        }
      }
    }
  }, [location, tables]);

  // 获取餐桌数据
  const fetchTables = async () => {
    setLoading(true);
    try {
      const response = await tablesService.getTableList({
        page: 1,
        pageSize: 100 // 获取足够多的餐桌数据
      });
      if (response.code === 0 && response.data) {
        setTables(response.data.list);
      } else {
        message.error(response.message || '获取餐桌失败');
      }
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      message.error('获取餐桌数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取区域数据
  const fetchAreas = async () => {
    setAreasLoading(true);
    try {
      const response = await areasService.getAreaList({
        page: 1,
        pageSize: 50 // 获取足够多的区域数据
      });
      if (response.code === 0 && response.data) {
        setAreas(response.data.list);
      } else {
        message.error(response.message || '获取区域失败');
      }
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      message.error('获取区域数据失败');
    } finally {
      setAreasLoading(false);
    }
  };

  // 过滤餐桌
  const filteredTables = tables.filter(table => {
    const matchesSearch = searchQuery === '' || 
      table.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      (table.area && table.area.toLowerCase().includes(searchQuery.toLowerCase()));
    
    // 只过滤区域，不再过滤状态
    const matchesAreaTab = areaTab === 'all' || 
      table.areaId.toString() === areaTab;
    
    return matchesSearch && matchesAreaTab;
  });

  // 处理餐桌点击
  const handleTableClick = (table: Table) => {
    // 基于processingTrade判断状态
    const status: TableStatus = table.processingTrade ? 'occupied' : 'free';
    
    if (status === 'free') {
      navigateToOrderPage(table);
    } else if (status === 'occupied') {
      navigateToOrderDetail(table);
    }
  };

  // 导航到点餐页面
  const navigateToOrderPage = (table: Table) => {
    navigate(`/order-detail?tableId=${table.id}&mode=new`);
  };

  // 导航到订单详情页面
  const navigateToOrderDetail = (table: Table) => {
    navigate(`/orders/${table.processingTrade}`);
  };

  // 返回首页
  const handleBack = () => {
    navigate('/dashboard');
  };

  // 渲染餐桌卡片
  const renderTableCard = (table: Table) => {
    const status = table.processingTrade ? 'occupied' : 'free';
    
    return (
      <Card 
        key={table.id} 
        className={`table-card table-card-${status}`}
        onClick={() => handleTableClick(table)}
      >
        <div className="table-content">
          <div className="table-header">
            <h3 className="table-name">{table.name}</h3>
            <div className={`table-status-badge ${status === 'free' ? 'status-free' : 'status-occupied'}`}>
              {getStatusText(status)}
            </div>
          </div>
          
          <div className="table-info">
            <div className="table-info-item">
              <HomeOutlined className="table-info-icon" />
              <span className="table-info-text">{table.area || '未分区'}</span>
            </div>
            <div className="table-info-item">
              <UserOutlined className="table-info-icon" />
              <span className="table-info-text">{table.seats || 0}人桌</span>
            </div>
          </div>
        </div>
        
        <div className="table-action">
          <Button 
            variant={status === 'free' ? 'primary' : 'secondary'}
            fullWidth
            size="small"
          >
            {status === 'free' ? '开始点餐' : '查看订单'}
          </Button>
        </div>
      </Card>
    );
  };

  // 渲染区域 Tabs
  const renderAreaTabs = () => {
    return (
      <Tabs 
        className="area-tabs" 
        activeKey={areaTab} 
        onChange={setAreaTab}
        size="large"
      >
        <TabPane tab="全部区域" key="all" />
        {areas.map(area => (
          <TabPane tab={area.name} key={area.id.toString()} />
        ))}
      </Tabs>
    );
  };

  return (
    <Layout className="order-station-layout">
      <div className="order-station-header">
        <div className="header-left">
          <AntButton 
            className="back-button" 
            type="text" 
            icon={<ArrowLeftOutlined />} 
            size="large" 
            onClick={handleBack} 
          />
          <h1 className="page-title">餐桌管理</h1>
        </div>
        <div className="header-right">
          <Tooltip title="管理餐桌">
            <Button 
              variant="primary" 
              icon={<PlusOutlined />}
              onClick={() => navigate('/tables')}
            >
              管理餐桌
            </Button>
          </Tooltip>
        </div>
      </div>

      <div className="main-container">
        <div className="search-container">
          <Search 
            placeholder="搜索餐桌名称或区域..." 
            allowClear 
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            onSearch={setSearchQuery}
            size="large"
            className="search-input"
          />
        </div>
        
        {/* 区域筛选标签页 */}
        {areasLoading ? (
          <div className="loading-container">
            <Spin size="large" tip="加载区域中..." />
          </div>
        ) : (
          renderAreaTabs()
        )}
        
        <div className="tables-grid">
          {loading ? (
            <div className="loading-container">
              <Spin size="large" tip="加载餐桌中..." />
            </div>
          ) : filteredTables.length > 0 ? (
            filteredTables.map(renderTableCard)
          ) : (
            <div className="empty-container">
              <Empty 
                description="没有找到符合条件的餐桌"
                image={Empty.PRESENTED_IMAGE_SIMPLE}
              />
            </div>
          )}
        </div>
      </div>
    </Layout>
  );
};

export default OrderStationPage; 